package middleware

import (
	"time"

	"supershare/backend/models"

	"github.com/beego/beego/v2/core/config"
	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"github.com/golang-jwt/jwt/v5"
)

// AuthController 处理认证相关请求
type AuthController struct {
	web.Controller
}

// JWTClaims 自定义JWT声明
type JWTClaims struct {
	UserId   int64  `json:"user_id"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

// generateToken 生成JWT令牌
func GenerateToken(admin *models.Admin) (string, int64, error) {
	// 获取JWT配置
	secret, err := config.String("jwtsecret")
	if err != nil {
		return "", 0, err
	}

	expire, err := config.Int64("jwtexpire")
	if err != nil {
		expire = 86400 // 默认24小时
	}

	// 设置过期时间
	expiresAt := time.Now().Add(time.Duration(expire) * time.Second).Unix()

	// 创建JWT声明
	claims := JWTClaims{
		UserId:   admin.Id,
		Username: admin.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Unix(expiresAt, 0)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "supershare",
		},
	}

	// 创建令牌
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// 签名令牌
	tokenString, err := token.SignedString([]byte(secret))
	if err != nil {
		return "", 0, err
	}

	return tokenString, expiresAt, nil
}

// JWTMiddleware JWT认证中间件
func JWTMiddleware() web.FilterFunc {
	return func(ctx *context.Context) {
		// 跳过登录接口的认证
		if ctx.Request.URL.Path == "/api/auth/login" {
			return
		}

		// 获取Authorization头
		auth := ctx.Input.Header("Authorization")
		if auth == "" {
			ctx.Output.Status = 401
			ctx.Output.JSON(map[string]interface{}{
				"success": false,
				"message": "token,未授权访问",
			}, false, false)
			return
		}

		// 处理Bearer前缀
		tokenString := auth
		if len(auth) > 7 && auth[:7] == "Bearer " {
			tokenString = auth[7:]
		}

		// 解析JWT令牌
		secret, _ := config.String("jwtsecret")
		token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
			return []byte(secret), nil
		})

		if err != nil || !token.Valid {
			ctx.Output.Status = 401
			ctx.Output.JSON(map[string]interface{}{
				"success": false,
				"message": "无效的令牌",
			}, false, false)
			return
		}

		// 获取令牌中的用户信息
		claims, ok := token.Claims.(*JWTClaims)
		if !ok {
			ctx.Output.Status = 401
			ctx.Output.JSON(map[string]interface{}{
				"success": false,
				"message": "无效的令牌声明",
			}, false, false)
			return
		}
		// 将用户ID存储在上下文中，以便后续使用
		ctx.Input.SetData("user_id", claims.UserId)
		ctx.Input.SetData("username", claims.Username)
	}
}
